package com.biscuit.page.basicservice.design.flow_limit.factory;

import com.biscuit.page.basicservice.design.flow_limit.FlowLimitTypeEnum;
import com.biscuit.page.basicservice.design.flow_limit.strategy.FlowLimitHandlerStrategy;
import com.biscuit.page.basicservice.design.flow_limit.strategy.NotFlowLimitHandlerStrategy;
import com.biscuit.page.basicservice.design.flow_limit.strategy.TokenBucketFlowLimitHandlerStrategy;
import com.biscuit.page.basicservice.utils.BaseExceptionUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author biscuit
 * @create 2024年07月29日 15:23
 */
public class FlowLimitStrategyFactory {

    private static final Map<FlowLimitTypeEnum, FlowLimitHandlerStrategy> factoryMap;


    static {
        factoryMap = new HashMap<>(1);
        factoryMap.put(FlowLimitTypeEnum.NOT_FLOW_LIMIT, new NotFlowLimitHandlerStrategy());
        factoryMap.put(FlowLimitTypeEnum.TOKEN_BUCKET_FLOW_LIMIT, new TokenBucketFlowLimitHandlerStrategy());
    }

    public static FlowLimitHandlerStrategy create(int type) {
        // 根据类型获取限流策略枚举
        FlowLimitTypeEnum typeEnum = FlowLimitTypeEnum.getEnumByType(type);
        BaseExceptionUtil.throwException(Objects.nonNull(typeEnum), "限流策略不存在");

        // 获取策略实现
        FlowLimitHandlerStrategy strategy = factoryMap.get(typeEnum);

        // 策略初始化
        strategy.init();
        return strategy;
    }

}
